﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using MongoDB.Bson;

namespace DataCollectService
{
    /// <summary>
    /// 数据接口帮助类
    /// </summary>
    public class DataInterfaceHelper
    {
        //设备协议集合
        public Dictionary<string, string> deviceProtocol = new Dictionary<string, string>();
        //协议列表
        public List<Protocol> listProtocal = new List<Protocol>();

        public DataInterfaceHelper(Dictionary<string, string> _deviceProtocol)
        {
            this.deviceProtocol = _deviceProtocol;
        }
        /// <summary>
        /// 按KV值进行数据库存储
        /// </summary>
        /// <param name="deviceNo"></param>
        /// <param name="CJTime"></param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public void insertKV(string deviceNo,DateTime CJTime,string key,string value,int saveTime)
        {
            //通过deviceNo,获取当前设备走的存储协议
            if(deviceProtocol.ContainsKey(deviceNo))
            {
                string protocalName = deviceProtocol[deviceNo];
                if(protocalName == "mssql")
                {
                    var protocal = listProtocal.Where(x => x.DBConfigType == "mssql").FirstOrDefault();
                    insertData_Mssql(protocal, deviceNo, key, value, CJTime);

                }
                //else if(protocalName == "mongodb")
                //{
                //    insertData_Mongodb();
                //}
                else if(protocalName == "redis")
                {
                    var protocal = listProtocal.Where(x => x.DBConfigType == "redis").FirstOrDefault();
                    insertData_Redis(protocal, deviceNo, key, value, CJTime, saveTime);
                }
            }
            else
            {
                //记录日志
                Log.SaveNote("当前设备" + deviceNo + "未配置设备存储协议,key为:" + key + ",value为:" + value + "");
            }
        }
        /// <summary>
        /// 通过JSON字符串存储数据库
        /// </summary>
        /// <param name="deviceNo"></param>
        /// <param name="CJTime"></param>
        /// <param name="paramDetail"></param>
        public void insertJSON(MongoDBCJRet ret)
        {
            //通过deviceNo,获取当前设备走的存储协议
            if (deviceProtocol.ContainsKey(ret.DeviceNo))
            {
                string protocalName = deviceProtocol[ret.DeviceNo];

                if (protocalName == "mongodb")
                {
                    var protocal = listProtocal.Where(x => x.DBConfigType == "mongodb").FirstOrDefault();
                    insertData_Mongodb(protocal,ret);
                }
            }
            else
            {
                //记录日志
                Log.SaveNote("当前设备" + ret.DeviceNo + "未配置设备存储协议,JSON格式为:"+ret.ToJson());
            }
        }

        /// <summary>
        /// 数据库新增逻辑
        /// </summary>
        public void insertData_Mssql(Protocol protocal, string deviceNo, string key, string value, DateTime CJTime)
        {
            string tableName = "CJ_Record";
            //支持分库的操作
            if(protocal.IsSubTable == 1)
            {
                switch (protocal.SubTableType)
                {
                    case "按月分表":tableName = "CJ_Record_" + DateTime.Now.ToString("yyyyMM"); break;
                    case "按日分表": tableName = "CJ_Record_" + DateTime.Now.ToString("yyyyMMdd"); break;
                    case "按周分表": tableName = "CJ_Record_" + DateTime.Now.ToString("yyyyMM")+DateTime.Now.DayOfWeek.ToString(); break;
                    case "按设备分表": tableName = "CJ_Record_" + deviceNo; break;
                }
                //按表名建表
                string sql = @"IF NOT EXISTS (
                                    SELECT * FROM INFORMATION_SCHEMA.TABLES 
                                    WHERE TABLE_NAME = '"+ tableName + @"' 
                                )
                               begin
                                 CREATE TABLE [dbo].["+tableName+@"](
	                                [RID] [int] IDENTITY(1,1) NOT NULL,
	                                [EquipID] [int] NULL,
	                                [VarName] [nvarchar](50) NULL,
	                                [VarValue] [nvarchar](50) NULL,
	                                [CreateTime] [datetime] NULL,
                                    CONSTRAINT [PK_"+tableName+@"] PRIMARY KEY CLUSTERED 
                                (
	                                [RID] ASC
                                    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
                                    ) ON [PRIMARY]
                               end
                              ";
                DbHelperSQL.Query(sql, protocal.ConnStr);
            }
            //插入数据库
            DbHelperSQL.Query("insert into " + tableName + "(EquipID,VarName,VarValue,CreateTime) values(@EquipID,@VarName,@VarValue,@CreateTime) ", protocal.ConnStr, new SqlParameter[] {
                new SqlParameter("EquipID",deviceNo),
                new SqlParameter("VarName",key),
                new SqlParameter("VarValue",value),
                new SqlParameter("CreateTime",CJTime.ToString("yyyy-MM-dd HH:mm:ss"))
            });
        }
        /// <summary>
        /// mongodb新增逻辑
        /// </summary>
        /// <param name="protocal"></param>
        public void insertData_Mongodb(Protocol protocal, MongoDBCJRet ret)
        {
            string mongoDBConnStr = protocal.ConnStr.Split(';')[0];
            string mongoDBDatabase = protocal.ConnStr.Split(';')[1];
            MongoDBHelper.SetConfig(mongoDBConnStr, mongoDBDatabase);
            MongoDBHelper.InsertOne<MongoDBCJRet>("CJ_Record", ret);
        }
        /// <summary>
        /// Redis新增逻辑
        /// </summary>
        /// <param name="protocal"></param>
        public void insertData_Redis(Protocol protocal, string deviceNo, string key, string value, DateTime CJTime,int saveTime)
        {
            List<string> listConnAddress = new List<string>();
            listConnAddress.Add(protocal.ConnStr);
            RedisHelper redisHelper = new RedisHelper(listConnAddress);
            string name = deviceNo + "_" + key + "_" + CJTime.ToString("yyyyMMddHHmmss");
            //默认保存时长，2个月
            DateTime expireTime = DateTime.Now.AddDays(60);
            if(saveTime!=0)
            {
                expireTime = DateTime.Now.AddDays(saveTime);
            }

            redisHelper.Set(name, value, expireTime, long.Parse(protocal.DBNum.ToString()));
        }

    }
}
